<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
         v-if="!viewFlag"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:funding_annual:add']"
        >新增</el-button>
      </el-col>

    </el-row>

    <el-table v-loading="loading" :data="funding_annualList" @selection-change="handleSelectionChange">
      <el-table-column label="年度" align="center" prop="year">
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.isEditing"
            v-model="scope.row.year"
            placeholder="请输入年度"
          />
          <span v-else>{{ scope.row.year }}</span>
        </template>
      </el-table-column>

      <el-table-column label="自治区财政科技资金（万元）" width="200" align="center" prop="provincialFunds">
        <template slot-scope="scope">
          <el-input-number
            v-if="scope.row.isEditing"
            v-model="scope.row.provincialFunds"
            placeholder="自治区财政科技资金"
            :precision="2"
            :step="0.01"
            controls-position="right"
            style="width: 100%"
          />
          <span v-else>{{ scope.row.provincialFunds }}</span>
        </template>
      </el-table-column>
      <el-table-column label="市财政资金（万元）" align="center" prop="municipalFunds">
        <template slot-scope="scope">
          <el-input-number
            v-if="scope.row.isEditing"
            v-model="scope.row.municipalFunds"
            placeholder="市财政资金"
            :precision="2"
            :step="0.01"
            controls-position="right"
            style="width: 100%"
          />
          <span v-else>{{ scope.row.municipalFunds }}</span>
        </template>
      </el-table-column>
      <el-table-column label="自筹资金（万元）" align="center" prop="selfFunds">
        <template slot-scope="scope">
          <el-input-number
            v-if="scope.row.isEditing"
            v-model="scope.row.selfFunds"
            placeholder="自筹资金"
            :precision="2"
            :step="0.01"
            controls-position="right"
            style="width: 100%"
          />
          <span v-else>{{ scope.row.selfFunds }}</span>
        </template>
      </el-table-column>
      <el-table-column label="其他渠道资金（万元）" align="center" prop="otherFunds">
        <template slot-scope="scope">
          <el-input-number
            v-if="scope.row.isEditing"
            v-model="scope.row.otherFunds"
            placeholder="其他渠道资金"
            :precision="2"
            :step="0.01"
            controls-position="right"
            style="width: 100%"
          />
          <span v-else>{{ scope.row.otherFunds }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总金额（万元）" align="center" prop="totalAmount">
        <template slot-scope="scope">
          <span v-if="scope.row.isEditing">{{ calculateTotal(scope.row) }}</span>
          <span v-else>{{ scope.row.totalAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remarks">
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.isEditing"
            v-model="scope.row.remarks"
            placeholder="备注"
          />
          <span v-else>{{ scope.row.remarks }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="!viewFlag" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.isEditing"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="saveRow(scope.row)"
          >保存</el-button>
          <el-button
            v-if="scope.row.isEditing"
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="cancelEdit(scope.row)"
          >取消</el-button>
          <el-button
            v-if="(!scope.row.isEditing && !scope.row.isNew) "
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="editRow(scope.row)"
            v-hasPermi="['system:funding_annual:edit']"
          >修改</el-button>
          <el-button
            v-if="!scope.row.isEditing && !scope.row.isNew"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:funding_annual:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listFunding_annual, getFunding_annual, delFunding_annual, addFunding_annual, updateFunding_annual } from "@/api/sci/funding_annual";

export default {
  name: "FundingAnnual",

  props: {
    projectId: {
      type: [String, Number], // 根据实际类型选择
      default: null
    },
    viewFlag: {
      type: Boolean,
      default: false
    },
  },
   data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目经费年度构成表格数据
      funding_annualList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: this.projectId,
        year: null,
        totalAmount: null,
        provincialFunds: null,
        municipalFunds: null,
        selfFunds: null,
        otherFunds: null,
        remarks: null,
      },
      // 表单参数
      form: {
        projectId: this.projectId,
      },
      // 表单校验
      rules: {
        projectId: [
          { required: true, message: "项目ID不能为空", trigger: "blur" }
        ],
        year: [
          { required: true, message: "年度不能为空", trigger: "blur" }
        ],
        provincialFunds: [
          { required: true, message: "自治区财政科技资金不能为空", trigger: "blur" }
        ],
        municipalFunds: [
          { required: true, message: "盟市财政资金不能为空", trigger: "blur" }
        ],
        selfFunds: [
          { required: true, message: "自筹资金不能为空", trigger: "blur" }
        ],
        otherFunds: [
          { required: true, message: "其他渠道资金不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    if(this.projectId !== null){
      this.queryParams.projectId = this.projectId;
      this.getList();
    }else{
      this.loading=false;
    }
  },
  watch: {
    projectId(newVal) {
      // 当 projectId 变化时，更新查询参数并重新获取列表
      if (newVal === null) {
        this.queryParams.projectId = null;
        this.funding_annualList = [];
        this.total = 0;
        return;
      }
      this.queryParams.projectId = newVal;
      this.getList();
    }
  },
  methods: {
    /** 查询项目经费年度构成列表 */
    getList() {
      this.loading = true;
      listFunding_annual(this.queryParams).then(response => {
        this.funding_annualList = response.rows;
        this.total = response.total;
        this.loading = false;
        // 将初始数据传递给父组件
        this.$emit("update:fundingAnnualData", this.funding_annualList);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        annualId: null,
        projectId: null,
        year: null,
        totalAmount: null,
        provincialFunds: null,
        municipalFunds: null,
        selfFunds: null,
        otherFunds: null,
        remarks: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        isDeleted: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.annualId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      const newRow = {
        annualId: null, // 新增数据没有ID
        projectId: this.projectId,
        year: null,
        totalAmount: null,
        provincialFunds: 0.00,
        municipalFunds: 0.00,
        selfFunds: 0.00,
        otherFunds: 0.00,
        remarks: null,
        isEditing: true,
        isNew: true
      };
      this.funding_annualList.push(newRow); // 添加到末尾而不是开头
      // 将更新后的数据传递给父组件
      this.$emit("update:fundingAnnualData", this.funding_annualList);
    },

     /** 计算总金额 */
    calculateTotal(row) {
      const provincial = parseFloat(row.provincialFunds) || 0;
      const municipal = parseFloat(row.municipalFunds) || 0;
      const self = parseFloat(row.selfFunds) || 0;
      const other = parseFloat(row.otherFunds) || 0;
      return (provincial + municipal + self + other).toFixed(2);
    },
    /** 编辑行 */
    editRow(row) {
      row.isEditing = true;
      // 将更新后的数据传递给父组件
      this.$emit("update:fundingAnnualData", this.funding_annualList);
    },

    /** 保存行 */
    saveRow(row) {
      // 验证必填字段
      if (!row.year) {
        this.$message.error("年度不能为空");
        return;
      }
      if (row.provincialFunds === null || row.provincialFunds === undefined || row.provincialFunds === '') {
        this.$message.error("自治区财政科技资金不能为空");
        return;
      }
      if (row.municipalFunds === null || row.municipalFunds === undefined || row.municipalFunds === '') {
        this.$message.error("盟市财政资金不能为空");
        return;
      }
      if (row.selfFunds === null || row.selfFunds === undefined || row.selfFunds === '') {
        this.$message.error("自筹资金不能为空");
        return;
      }
      if (row.otherFunds === null || row.otherFunds === undefined || row.otherFunds === '') {
        this.$message.error("其他渠道资金不能为空");
        return;
      }
      // / 设置总金额为计算值
      row.totalAmount = this.calculateTotal(row);
      // 保存行，不提交数据库
      row.isEditing = false;
      row.isNew = false; // 标记为已保存但未提交到数据库

      // 将更新后的数据传递给父组件
      this.$emit("update:fundingAnnualData", this.funding_annualList);
    },

    /** 取消编辑 */
    cancelEdit(row) {
      if (row.isNew) {
        // 如果是新行，直接从列表中删除
        const index = this.funding_annualList.indexOf(row);
        if (index !== -1) {
          this.funding_annualList.splice(index, 1);
        }
      } else {
        // 如果是编辑现有行，恢复原始数据
        // 这里需要从父组件获取原始数据，暂时先简单处理
        const index = this.funding_annualList.indexOf(row);
        if (index !== -1) {
          // 重置编辑状态
          row.isEditing = false;
        }
      }

      // 将更新后的数据传递给父组件
      this.$emit("update:fundingAnnualData", this.funding_annualList);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const annualId = row.annualId || this.ids
      getFunding_annual(annualId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改项目经费年度构成";
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除项目经费年度为"' + row.year + '"的数据项？').then(() => {
        const index = this.funding_annualList.indexOf(row);
        if (index !== -1) {
          this.funding_annualList.splice(index, 1);
        }
        // 将更新后的数据传递给父组件
        this.$emit("update:fundingAnnualData", this.funding_annualList);
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/funding_annual/export', {
        ...this.queryParams
      }, `funding_annual_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
